<template>
  <van-button
    v-if="is_followed"
    class="follow-btn"
    round
    size="small"
    :loading="isFollowLoading"
    @click="onFollow"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="isFollowLoading"
    @click="onFollow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'follow-user',
  data () {
    return {
      isFollowLoading: false
    }
  },

  model: {
    prop: 'is_followed',
    event: 'update-follow'
  },

  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    user_id: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    async onFollow () {
      this.isFollowLoading = true
      try {
        if (this.is_followed) {
          // 关注状态 点击取消关注
          await deleteFollow(this.user_id)
        } else {
          // 取消状态 点击加关注
          await addFollow(this.user_id)
        }
        // this.article.is_followed = !this.article.is_followed
        this.$emit('update-follow', !this.is_followed)
      } catch (err) {
        if (err.response && err.response.status === 400) {
          this.$toast('禁止套娃，你不能自己关注自己')
        } else if (err.response && err.response.status === 401) {
          this.$toast('请先登录')
        } else {
          this.$toast('操作失败,请稍后再试')
        }
      }
      this.isFollowLoading = false
    }
  }
}
</script>

<style></style>
